package com.xh.common.thread.ext.executor;

import com.xh.common.thread.ext.queue.LevelBlockingQueue;

import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class LevelInternalExecutor {

    private final int mLevel;
    private final LevelConfig mConfig;

    private final LevelThreadPoolExecutor mOuter;

    private final ReentrantLock mLock;
    // 保存当前线程的集合 Access only under lock
    private final HashSet<LevelWorker> mWorkers;

    private final AtomicInteger mWorkCount;

    // 跟踪最大达到的线程池大小 Access only under lock
    private int mLargestPoolSize;
    // 完成的任务数 Access only under lock
    private long mCompletedTaskCount;

    public LevelInternalExecutor(LevelThreadPoolExecutor executor, int level, LevelConfig config) {
        mOuter = executor;
        mLevel = level;
        mConfig = config;

        mWorkCount = new AtomicInteger();

        mWorkers = new HashSet<>();
        mLock = new ReentrantLock();
    }

    int getLevel() {
        return mLevel;
    }

    LevelConfig getConfig() {
        return mConfig;
    }

    AtomicInteger getWorkCount() {
        return mWorkCount;
    }

    public boolean execute(Command command) {
        LevelExecutorDetector detector = mOuter.mDetector;

        // 如果没有达到核心线程数，则创建新线程，执行当前任务。
        int count = mWorkCount.get();
        if (count < mConfig.mCorePoolSize) {
            if (addWorker(command, true)) {

                if (detector != null) {
                    detector.onAddCoreWorker(command, mLevel);
                }

                return true;
            }
        }

        // 如果当前的线程存在空闲，就把任务提交给空闲线程
        LevelBlockingQueue<Command> workQueue = mOuter.mWorkQueue;
        if (mOuter.isRunning() && workQueue.offerWait(command, mLevel)) {

            if (detector != null) {
                detector.onOfferWaitQueue(command, mLevel);
            }

            return true;
        }

        // 如果没有达到最大线程数，则创建新线程，执行队头任务。
        if (count < mConfig.mMaximumPoolSize) {
            // 如果队列不为空，则把当前任务放进去。
            if (mOuter.isRunning() && workQueue.offer(command)) {
                // 如果放进去后又停了，就移除
//                if (!mOuter.isRunning()) {
//                    workQueue.remove(command);
//                    return false;
//                }
            }
            // 新建线程，具体能不能新建成功都无所谓。
            addWorker(null, false);

            if (detector != null) {
                detector.onAddExtraWorker(command, mLevel);
            }

            // 因为已经把任务添加进去了，这里就只需要返回true
            return true;
        }
        return false;
    }

    boolean addWorker(Command firstTask, boolean core) {
        // 1.先判断能不能创建新的线程，如果能就先把count+1，后面如果添加失败会回滚。
        // 这里借鉴系统的锁的写法提高效率。
        retry:
        for (;;) {
            int wc = mWorkCount.get();
            int rs = mOuter.getStatus();

            // Check if queue empty only if necessary.
            if (rs >= LevelThreadPoolExecutor.SHUTDOWNED &&
                    !(rs == LevelThreadPoolExecutor.SHUTDOWNED &&
                            firstTask == null &&
                            !mOuter.mWorkQueue.isEmpty())) {
                return false;
            }

            for (;;) {
                if (wc >= (core ? mConfig.mCorePoolSize : mConfig.mMaximumPoolSize)) {
                    return false;
                }
                if (mWorkCount.compareAndSet(wc, wc + 1)) {
                    break retry;
                }
                wc = mWorkCount.get();
                if (mOuter.getStatus() != rs) {
                    continue retry;
                }
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        // 2.创建新的线程
        boolean workerStarted = false;
        boolean workAdded = false;

        LevelWorker w = null;
        try {
            // 2.1新创建线程
            w = new LevelWorker(mOuter, this, firstTask);
            final Thread t = w.getThread();

            if (t != null) {
                mLock.lock();

                try {

                    int rs = mOuter.getStatus();

                    if (rs < LevelThreadPoolExecutor.SHUTDOWNED ||
                            (rs == LevelThreadPoolExecutor.SHUTDOWNED && firstTask == null)) {
                        if (t.isAlive()) {
                            throw new IllegalThreadStateException();
                        }

                        // 2.2将线程添加到集合
                        mWorkers.add(w);

                        // 2.3记录最大的线程数
                        int s = mWorkers.size();
                        if (s > mLargestPoolSize) {
                            mLargestPoolSize = s;
                        }
                        workAdded = true;
                    }
                } finally {
                    mLock.unlock();
                }
                // 2.4启动线程
                if (workAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            // 2.5线程添加失败要回滚
            if (!workerStarted) {
                addWorkerFailed(w);
            }
        }
        return workerStarted;
    }

    private void addWorkerFailed(LevelWorker w) {
        mLock.lock();

        try {
            // 1.回滚集合中添加进去的线程
            if (w != null) {
                mWorkers.remove(w);
            }

            // 2.回滚之前递增的线程数
            mWorkCount.decrementAndGet();

        } finally {
            mLock.unlock();
        }
    }

    /**
     *
     * @param w
     * @param completedAbruptly if the worker died due to user exception
     */
    void processWorkerExit(LevelWorker w, boolean completedAbruptly) {
        if (completedAbruptly) {
            mWorkCount.decrementAndGet();
        }

        mLock.lock();

        try {
            mCompletedTaskCount += w.getCompletedTasks();
            mWorkers.remove(w);
        } finally {
            mLock.unlock();
        }

        if (!completedAbruptly) {
            int min = mConfig.mAllowCoreThreadTimeOut ? 0 : mConfig.mCorePoolSize;
            if (min == 0 && mOuter.mWorkQueue.peek(mLevel) != null) {
                min = 1;
            }
            if (mWorkCount.get() >= min) {
                return;
            }
            addWorker(null, false);
        }
    }
}
